package com.suixun.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtil {

	public final static String YEAR = "年";
	public final static String MONTH = "月";
	public final static String DATE = "日";
	public final static String HOUR = "时";
	public final static String MINUTE = "分";
	public final static String SECOND = "秒";
    /**
     * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
     * 
     * @param time 需要格式化的时间 如"2014-07-14 19:01:45"
     * @param pattern 输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
     *        <p/>
     *        如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
     * @return time为null，或者时间格式不匹配，输出空字符""
     */
    public static String formatDisplayTime(String time, String pattern) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != null) {
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(time);
                Date today = new Date();
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    SimpleDateFormat halfDf = new SimpleDateFormat("yyyy-MM-dd");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy-MM-dd").format(tDate);
                    } else {

                        if (dTime < tMin) {
                            // display = "刚刚";
                            display = new SimpleDateFormat("HH:mm").format(tDate);
                        } else if (dTime < tHour) {
                            // display = (int) Math.ceil(dTime / tMin) + "分钟前";
                            display = new SimpleDateFormat("HH:mm").format(tDate);
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            // display = (int) Math.ceil(dTime / tHour) + "小时前";
                            display = new SimpleDateFormat("HH:mm").format(tDate);
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            // 昨天 时间
                            display = "昨天" + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = halfDf.format(tDate);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return display;
    }

    /*
     * 获取手机号服务周期
     */
    public static Date getServiceEndTime(Date starttime, int type, int length) {
        try {

            if (type == 1) {
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                c.setTime(starttime);
                c.setTime(sdf.parse(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-"
                        + "01"));
                c.add(c.YEAR, length);
                c.add(c.DATE, -1);
                return c.getTime();
            } else if (type == 2) {
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                c.setTime(starttime);
                c.setTime(sdf.parse(c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 2) + "-"
                        + "01"));
                c.add(c.MONTH, length);
                c.add(c.DATE, -1);
                return c.getTime();
            }

        } catch (Exception e) {
            
        }
        return null;
    }
    
    /**
     * 格式化时间
     * 
     * @param time 需要格式化的时间 如"2014-07-14 19:01:45"
     * @param pattern 输入参数time的时间格式 如:"yyyy-MM-dd HH:mm:ss"
     *        <p/>
     *        如果为空则默认使用"yyyy-MM-dd HH:mm:ss"格式
     * @return time为null，或者时间格式不匹配，输出空字符""
     */
    public static String formatDateToString(Date date, String pattern) {
    	if(date==null)
    		return "";
    	if(pattern==null || pattern.trim().equals(""))
    		pattern="yyyy-MM-dd HH:mm:ss";
            try {
            	return new SimpleDateFormat(pattern).format(date);
                
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        

    }
    
    public static Date formatStringToTime(String time, String pattern) {
    	if(time==null)
    		return null;
    	if(pattern==null || pattern.trim().equals(""))
    		pattern="HH:mm";
    	//if(time.length()<10)
    		//time="2000-01-01 "+time;
            try {
            	Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                return sdf.parse(time);
            	//return new Date(time);// new SimpleDateFormat(pattern)..format(date);
                
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        

    }
    
    /**
     * 
     * <p>Title: compareToTime2</p>
     * <p> 功能描述:比较：时，分 ,date1小于date2为1,date1大于date2为2,date1等于date2为3</p>
      * @param date1 
     * @param date2 
     * @return
     * @throws ParseException 
     */
    public static int compareToTime2(Date time1,Date time2) throws ParseException{
    	String date1=new SimpleDateFormat("HHmm").format(time1);
    	String date2=new SimpleDateFormat("HHmm").format(time2);
    	if(Long.parseLong(date1)<Long.parseLong(date2)){
    		return 1;
    	}else if(Long.parseLong(date1)==Long.parseLong(date2)){
    		return 3;
    	}else{
    		return 2;
    	}
    }
    /**
     * 
     * <p>Title: compareTotime3</p>
     * <p> 功能描述:比较年月日时分，date1小于date2为1,date1大于date2为2,date1等于date2为3 </p>
     * @param date1 
     * @param date2 
     * @return
     * @throws ParseException 
     */
    public static  int compareTotime3(Date time1,Date time2) throws ParseException{
		String date1= new SimpleDateFormat("yyyyMMddHHmm").format(time1);
		String date2= new SimpleDateFormat("yyyyMMddHHmm").format(time2);
    	if(Long.parseLong(date1)<Long.parseLong(date2)){
    		return 1;
    	}else if(Long.parseLong(date1)==Long.parseLong(date2)){
    		return 3;
    	}else{
    		return 2;
    	}
    }
    /**
     * 
     * <p>Title: getTime</p>
     * <p> 功能描述:给日期中的指定时间（年，月，日，时，分，秒）增加或减少时间 </p>
     * @param time
     * @param str
     * @param num
     * @return
     */
    public static String getTime(Date time,String str,int num){
    	int year =0,month = 0,date = 0,hour = 0, minute = 0,second = 0;
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(time);
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH)+1;
		date = calendar.get(Calendar.DATE);
		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minute = calendar.get(Calendar.MINUTE);
		second = calendar.get(Calendar.SECOND);
		String dateTime = null;
    	switch (str) {
    		case YEAR :
    			year = year + num;
    			break;
    		case MONTH :
    			 month = month + num;
    			if (month > 12) {
    				int num1 = month / 12;
    				year = year + num1;
    				month = month % 12;
    			}
    			break;
    		case DATE :
    			date = date + num;
    			dateTime = getDateUp(hour, date, month, year);
    			break;
    		case HOUR :
    			hour = hour + num;
    			if (hour >= 24) {
    				date = date + (hour / 24);
    				dateTime = getDateUp(hour, date, month, year);
    			}
    			break;
    		case MINUTE :
    			minute = minute + num;
    			if (minute >= 60) {
    				hour = hour + (minute / 60);
    				if (hour >= 24) {
    					int hours = hour / 24;
        				date = date + hours;
        				dateTime = getDateUp(hour, date, month, year);
    				}
    				minute = minute % 60;
    			}
    			break;
    		case SECOND :
    			second = second + num;
    			if (second >= 60) {
    				int minutes = minute + (second / 60);
    				if (minutes >= 60) {
    					hour = hour + (minutes / 60);
    					if (hour >= 24) {
    						date = date + (hour / 24);
    						dateTime = getDateUp(hour, date, month, year);
    					}
    					minute = minute + (second % 60);;
    				}else {
    					minute = minutes;
    				}
    			}
    	}
    	if (dateTime == null) {
    		dateTime = new StringBuffer().append(String.valueOf(year)).append("-")
					.append(zeroize(String.valueOf(month), 2)).append("-")
					.append(zeroize(String.valueOf(date), 2)).append(" ")
					.append(zeroize(String.valueOf(hour), 2)).toString();
    	}
    	String newDate = new StringBuffer().append(dateTime).append(":")
    			.append(zeroize(String.valueOf(minute), 2)).append(":")
    			.append(zeroize(String.valueOf(second), 2)).toString();
    	
    	return newDate;
    }
    
    public static String getDateUp (int hour,int date,int month,int year) {
    	switch (month) {
			case 1 :
			case 3 :
			case 5 :
			case 7 :
			case 8 :
			case 10 :
			case 12 :
				if (date >31) {
					int num1 = date / 31;
					int num2 = month + num1;
					if (num2 > 12) {
						year = year + (num2 / 12);
						month = num2 % 12;
					}else {
						month = num2;
					}
					date = num1 % 31;
				}
					hour = hour % 24;
				break;
			case 4 :
			case 6 :
			case 9 :
			case 11 :
				if (date >30) {
					int num1 = date / 30;
					int num2 = month + num1;
					if (num2 > 12) {
						year = year + (num2 / 12);
						month = num2 % 12;
					}else {
						month = num2;
					}
					date = num1 % 30;
				}
					hour = hour % 24;
				break;
			case 2 :
				if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
					if (date >29) {
						int num1 = date / 29;
						int num2 = month + num1;
						if (num2 > 12) {
							year = year + (num2 / 12);
							month = num2 % 12;
						}else {
							month = num2;
						}
						date = num1 % 29;
					}
				}else {
					if (date >28) {
						int num1 = date / 28;
						int num2 = month + num1;
						if (num2 > 12) {
							year = year + (num2 / 12);
							month = num2 % 12;
						}else {
							month = num2;
						}
						date = num1 % 28;
					}
				}
					hour = hour % 24;
    	}
    	String newDate = new StringBuffer().append(String.valueOf(year)).append("-")
    				.append(zeroize(String.valueOf(month), 2)).append("-")
    				.append(zeroize(String.valueOf(date), 2)).append(" ")
    				.append(zeroize(String.valueOf(hour), 2)).toString();
    	return newDate;
    }
    
    /**
	 * 
	 * <p>Title: zeroize</p>
	 * <p> 功能描述:自动补零工具 </p>
	 * @param str 需要补零的数字，如"1"
	 * @param number 需要补到多少位数,如number=3,则为"001"
	 * @return
	 */
	public static String zeroize(String str,int number){
		if(str==null){
			return null;
		}
		if(str.length()>=number){
			return str;
		}else{
			int num=number-str.length();
			StringBuffer nStr=new StringBuffer();
			for(int i=0;i<num;i++){
				nStr.append("0");
			}
			nStr.append(str);
			return nStr.toString();
		}
	}
    
    public static void main(String[] args) throws ParseException{
    	Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2017-03-21 17:58:00");
    	String dateTime = DateUtil.getTime(date, MINUTE, 2);
    	System.out.println(dateTime);
        //System.out.println(DateUtil.getServiceEndTime(new Date(), 2, 1));
    }
}
